package com.mall.group_booking.service.impl;

import com.mall.common.response.CommonResponse;
import com.mall.constant.enums.CommonStatus;
import com.mall.constant.strings.MapMsg;
import com.mall.constant.strings.SuccessMsg;
import com.mall.entity.TbItmeSpec;
import com.mall.entity.bargain.BgOrder;
import com.mall.entity.groupbooking.GbItem;
import com.mall.group_booking.entity.GbItemVo;
import com.mall.group_booking.feign.OrderFeign;
import com.mall.group_booking.mapper.BookingItemMapper;
import com.mall.group_booking.service.BookingItemService;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.impl.recovery.AutorecoveringConnection;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RMap;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author White
 * @version 1.0
 * @email 616769721@qq.com
 * @date 2021/7/29 21:00
 */
@Service
public class BookingItemServiceImpl implements BookingItemService {

    @Autowired
    private BookingItemMapper bookingItemMapper;

    @Autowired
    private Redisson redisson;

    @Autowired
    private OrderFeign orderFeign;

    @Override
    public void addItemToRedis() {
        List<GbItemVo> gbItemList=bookingItemMapper.findByTime("2021-08-09 20:10:00");
        Map<Long, GbItemVo> maps = gbItemList.stream().collect(Collectors
                .toMap(GbItemVo::getSpecItemId, Function.identity(), (key1, key2) -> key2));
        RMap<Long, GbItemVo> itemMap = redisson.getMap(MapMsg.BOOKING_ITEM_REDIS_MAP);
        RLock lock = redisson.getLock(MapMsg.LOCK_BOOKING_ITEM_REDIS_MAP);
        try {
            lock.lock(5, TimeUnit.SECONDS);
            itemMap.clear();
            itemMap.putAll(maps);
        }finally {
            lock.unlock();
        }
    }

    @Override
    public List<GbItem> findItemList() {
        return bookingItemMapper.findItemList();
    }

    @Override
    public CommonResponse addOrder(Long specItemId,Long uid) {
        //查询具体商品信息
        TbItmeSpec itmeSpec = bookingItemMapper.findProductByItemSpecId(specItemId);
        //创建订单对象
        BgOrder bgOrder = new BgOrder();
        bgOrder.setUid(uid);
        bgOrder.setType("1");
        bgOrder.setPrice(itmeSpec.getPrice());
        bgOrder.setItemSpecId(specItemId);
        bgOrder.setCreateTime(new Date());
        bgOrder.setStatus("0");
        bgOrder.setOrderItemId(specItemId);
        //远程调用订单接口生成订单并返回订单号
        BgOrder order = orderFeign.createOrder(bgOrder);
        return new CommonResponse(CommonStatus.SUCCESS.getCode(), SuccessMsg.SUCCESS_CODE_200,order.getId());
    }



}
